<template>
  <BasicModal
    @register="registerModal"
    title="人工审核"
    width="70%"
    okText="最终合并"
    @cancel="handleClose"
    @ok="handleSubmit"
    :showOkBtn="Boolean(list.length)"
  >
    <BasicTable @register="registerTable" ref="basicTableRef">
      <template #bodyCell="{ column, index, record }">
        <template v-if="index === list.length - 2">
          <span v-if="column.dataIndex == 'index'">计算方式</span>

          <Select
            style="width: 100%"
            v-else
            v-model:value="selectValue[column.dataIndex]"
            :options="computedOptions"
            @change="(val) => selectChange(val, column.dataIndex)"
          />
        </template>
        <template v-else-if="index === list.length - 1">
          <span v-if="column.dataIndex == 'index'">最终结果</span>
          <Input
            v-else-if="!['index', 'checkDate', 'validUntil'].includes(column.dataIndex)"
            v-model:value="finallyData[column.dataIndex]"
          />
          <DatePicker
            v-else
            show-time
            v-model:value="finallyData[column.dataIndex]"
            format="YYYY-MM-DD HH:mm:ss"
          />
        </template>
        <template v-if="cellTtitle.includes(column.dataIndex as never) && index < list.length - 2">
          <div @click="handleCell($event, index, column.dataIndex, record[column.dataIndex])">{{
            record[column.dataIndex] || '-'
          }}</div>
        </template>
      </template>
    </BasicTable>
  </BasicModal>
</template>

<script setup lang="ts">
  import { ref, unref } from 'vue';
  import { Input, Select, DatePicker } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicTable, useTable } from '/@/components/Table';
  import { QSchemas } from '../index.data';
  import { getRecheckWaterMeterByCode, submitMergeData } from '/@/api/jd/water-box';
  import { useMessage } from '/@/hooks/web/useMessage';
  // import { isNumber } from '/@/utils/is';
  import dayjs from 'dayjs';

  const $emit = defineEmits(['success', 'register']);

  let handleCellData: any = {};

  const { createMessage } = useMessage();

  const [registerTable, { setTableData, setLoading, clearSelectedRowKeys }] = useTable({
    columns: QSchemas,
    clickToRowSelect: false,
    indexColumnProps: {
      dataIndex: 'index',
      width: 100,
    },

    rowSelection: {
      type: 'radio',
      getCheckboxProps: (record) => {
        record.disabled = !record.resultId;
        return record;
      },
      onSelect: (val, x, y, $event) => {
        const row = $event.target.parentNode.parentNode.parentNode.parentNode;
        const tds = row.querySelectorAll('td');
        clearAllbgColor();

        const index = list.value.findIndex((i) => i.resultId === val.resultId);

        finallyData.value = setSelectRowData(val);
        QSchemas.forEach((i, z) => {
          const div = tds[z + 2].querySelector('div');
          div.classList.add('active');

          handleCellData[`${index}_${i.dataIndex}`] = {
            value: ['checkDate', 'validUntil'].includes(i.dataIndex)
              ? dayjs(div.innerText)
              : div.innerText,
            dom: div,
          };
        });
        console.log(`handleCellData------------`, handleCellData);
      },
    },
    pagination: false,
  });
  const list = ref<any[]>([]);

  const basicTableRef = ref<HTMLElement | null>(null);

  let waterMeterCode = '';
  let record: any = '';

  const finallyData = ref({});

  enum SelectType {
    MAX,
    MIN,
    AVER,
    SELECT,
  }
  const selectValue = ref<any>({});
  let cellTtitle: any[] = [];

  const computedOptions = ref([
    { label: '最大值', value: 0 },
    { label: '最小值', value: 1 },
    { label: '平均值', value: 2 },
    { label: '选定值', value: 3 },
  ]);

  const [registerModal, { closeModal }] = useModalInner(async (data) => {
    console.log(data);
    setLoading(true);
    waterMeterCode = data.waterMeterCode;
    record = data;
    cellTtitle = QSchemas.map((i) => i.dataIndex);
    cellTtitle.forEach((i) => {
      selectValue.value[i] = 3;
      if (['checkDate', 'validUntil'].includes(i)) {
        finallyData.value[i] = dayjs(new Date());
      } else {
        finallyData.value[i] = '';
      }
    });
    const ret = await getRecheckWaterMeterByCode({
      waterMeterCode: waterMeterCode,
      taskId: record.taskId,
    });

    if (ret && ret.length) {
      list.value = [...ret, {}, {}];
    } else {
      list.value = [];
    }

    setLoading(false);
    setTableData(list.value);
  });

  //

  // 设置选中行数据
  const setSelectRowData = (rowData) => {
    let info: any = {
      resultId: rowData.resultId,
    };

    QSchemas.forEach((i) => {
      info[i.dataIndex as string] = rowData[i.dataIndex as string];
      if (['checkDate', 'validUntil'].includes(i.dataIndex as string)) {
        info[i.dataIndex as string] = dayjs(rowData[i.dataIndex as string]);
      }
      selectValue.value[i.dataIndex as string] = 3;
    });

    return info;
  };

  const deleteCellBgColor = (column) => {
    for (let i in handleCellData) {
      console.log(i, column);

      const item = i.split('_');
      if (item[1] === column) {
        handleCellData[i].dom.classList.remove('active');
        finallyData.value[column] = '';
        delete handleCellData[i];
      }
    }
    console.log(handleCellData);
  };

  // 全部清除选中
  const clearAllbgColor = () => {
    for (let i in handleCellData) {
      handleCellData[i].dom.classList.remove('active');
      finallyData.value = {};
      delete handleCellData[i];
    }
  };

  const selectChange = (_, column) => {
    deleteCellBgColor(column);
  };

  // 提取最新值
  const extractValue = (type, column, nowValue = '') => {
    let value = nowValue;
    if (selectValue.value[column] !== SelectType.SELECT) {
      value = formatValue(column, SelectType[type]) as any;
    } else {
      if (!value) {
        deleteCellBgColor(column);
      }
    }

    unref(finallyData)[column] = value;
  };

  // 值处理
  const formatValue = (column, type) => {
    const valueList: any[] = [];
    for (let i in handleCellData) {
      const item = i.split('_');
      if (item[1] === column) {
        valueList.push(handleCellData[i].value);
      }
    }

    switch (type) {
      case 'MAX':
        return valueList.sort((a, b) => b - a)[0];

      case 'MIN':
        return valueList.sort((a, b) => a - b)[0];

      case 'AVER':
        return (valueList.reduce((a, b) => Number(a) + Number(b), 0) / valueList.length).toFixed(2);
    }
  };

  // 单元格点击
  const handleCell = ($event, index, column, value) => {
    if (value === null) {
      value = undefined;
    }
    clearSelectedRowKeys();
    if (isNaN(Number(value)) && selectValue.value[column] !== SelectType.SELECT) {
      createMessage.warn('非数值类型不能进行比较');
      return;
    }
    // const { target } = $event;
    const flag = `${index}_${column}`;
    setCellBackground($event, selectValue.value[column], column);
    const obj = {
      value: ['checkDate', 'validUntil'].includes(column) ? dayjs(value) : value,
      dom: $event.target,
    };
    console.log(`handleCellData----------------`, handleCellData);

    if (selectValue.value[column] === SelectType.SELECT) {
      for (let i in handleCellData) {
        const item = i.split('_');
        if (item[1] === column) {
          delete handleCellData[i];
        }
      }
    } else {
      if (handleCellData.hasOwnProperty(flag)) {
        delete handleCellData[flag];
        return;
      }
    }
    handleCellData[flag] = obj;
    extractValue(
      selectValue.value[column],
      column,
      ['checkDate', 'validUntil'].includes(column) ? dayjs(value) : value,
    );
  };

  // 设置单元格背景色
  const setCellBackground = ($event, type, column) => {
    const { target } = $event;

    if (type === SelectType.SELECT) {
      if (target.classList.contains('active')) {
        target.classList.remove('active');
      } else {
        if (Object.keys(handleCellData).length) {
          for (let i in handleCellData) {
            const item = i.split('_');
            if (item[1] === column) {
              handleCellData[i].dom.classList.remove('active');
              target.classList.add('active');
              return;
            }
          }
        }
        target.classList.add('active');
      }
      return;
    }
    if (target.classList.contains('active')) {
      target.classList.remove('active');
    } else {
      target.classList.add('active');
    }
  };

  // 弹窗关闭
  const handleClose = () => {
    finallyData.value = {};
    handleCellData = {};
    list.value = [];
    closeModal();
  };

  // 合并提交
  const handleSubmit = async () => {
    let params: any = {};

    for (let i in unref(finallyData)) {
      params[i] = unref(finallyData)[i];
      if (['checkDate', 'validUntil'].includes(i) && unref(finallyData)[i]) {
        params[i] = dayjs(unref(finallyData)[i]).format('YYYY-MM-DD HH:mm:ss');
      }

      if (!unref(finallyData)[i]) {
        params[i] = unref(list)[unref(list).length - 3][i];
      }
    }

    params.waterMeterCode = waterMeterCode;
    delete params.resultId;
    console.log(params);
    await submitMergeData({ data: params, taskId: record.taskId });
    createMessage.success('操作成功');
    $emit('success');
    handleClose();
  };
</script>

<style lang="less" scoped>
  :deep(.ant-table-body) {
    max-height: auto !important;
    height: auto !important;

    .scrollbar {
      padding-bottom: 30px;
    }

    .ant-table-cell {
      cursor: pointer;

      .active {
        background: rgb(206, 215, 221) !important;
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        padding: 12px 8px;
      }
    }
  }
</style>
